package com.framework.plm.sec.service;

import java.util.Date;

import com.framework.plm.bas.param.GeneralParam;
import com.framework.plm.bas.service.impl.AbsPlmService;
import com.framework.plm.bas.util.PlmBasConstant;
import com.framework.plm.bas.util.UtilDatetime;
import com.framework.plm.org.vo.BasOrgUser;
import com.framework.plm.sec.bs.IPlmSecBS;
import com.framework.plm.sec.util.PlmSecConstant;
import com.framework.plm.sec.vo.LogonUserObject;
import com.framework.plm.sec.vo.UserAuthObject;
import com.framework.plm.sog.vo.BasLogLogin;

/**
 *
 */
public class LoginServiceImpl extends AbsPlmService implements ILoginService {

	private IPlmSecBS plmSecBS;

	public IPlmSecBS getPlmSecBS() {
		return plmSecBS;
	}

	public void setPlmSecBS(IPlmSecBS plmSecBS) {
		this.plmSecBS = plmSecBS;
	}

	public Object login(GeneralParam param) {

		LogonUserObject appsLogonUserVO = buidResult(param);

		addLoginLog(appsLogonUserVO);
		// throw new BasException("");

		return PlmBasConstant.SERVICE_OPER_SUCCESS;
	}

	private void addLoginLog(LogonUserObject appsLogonUserVO) {

		BasLogLogin logvo = new BasLogLogin();
		// logvo.setId(appsLogonUserVO.getLoginId());
		logvo.setUserId(appsLogonUserVO.getLoginId());
		logvo.setUserName(appsLogonUserVO.getUserName());
		logvo.setDeptCode(String.valueOf(appsLogonUserVO.getCurDept().getDeptId()));
		logvo.setDeptName(String.valueOf(appsLogonUserVO.getCurDept().getDeptName()));
		logvo.setLoginDate(new Date());
		// logvo.setLoginIp(httpRequest.getRemoteAddr());
		logvo.save();
	}

	public LogonUserObject buidResult(GeneralParam param) {

		String loginIp = param.getValueString(PlmSecConstant.LOGIN_IP);
		String loginId = param.getValueString(PlmSecConstant.LOGIN_USERNAME);

		BasOrgUser basOrgUser = getPlmSecBS().queryUserInfo(loginId);
		UserAuthObject userAuthObject = new UserAuthObject();
		userAuthObject.setLoginId(loginId);
		userAuthObject.setUserCode(basOrgUser.getUserId().toString());
		userAuthObject.setUserName(basOrgUser.getUserName());

		param.setValue(PlmSecConstant.USER_AUTH_OBJ, userAuthObject);

		LogonUserObject appsLogonUserVO = new LogonUserObject();
		appsLogonUserVO.setLogonDate(UtilDatetime.getDateString());
		appsLogonUserVO.setLogonTime(UtilDatetime.getTimeString());
		appsLogonUserVO.setLogonIp(loginIp);
		appsLogonUserVO.setLoginId(loginId);
		appsLogonUserVO.setUserName(basOrgUser.getUserName());
		appsLogonUserVO.setCurDept(basOrgUser.getBasOrgDept());

		param.setValue(PlmBasConstant.APP_USER, appsLogonUserVO);

		return appsLogonUserVO;
	}

}
